<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '仅保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '保存并入库',
      icon: '',
      type: 'primary',
      hidden: !isEdit || data.form.associationBillNo,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
    {
      title: '部分入库',
      icon: '',
      type: 'primary',
      hidden: !isEdit || !data.form.associationBillNo,
      click: (form: any) => {
        saveBtn(form, true, 1)
      },
    },
    {
      title: '全部入库',
      icon: '',
      type: 'primary',
      hidden: !isEdit || !data.form.associationBillNo,
      click: (form: any) => {
        saveBtn(form, true, 0)
      },
    },
  ]" :formInfo="[
    {
      label: '创建人员',
      value: 'createor',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12">
        <OrderInfo :data="data.productOrder" :produceTaskBillNo="route.query.produceTaskBillNo" />
        <CellBox title="基本信息" isTop>
          <FlexBox>
            <ElFormItemBox label="单据单号" prop="inStockBillNo">
              <ElInputBox :data="form" dataName="inStockBillNo" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据状态" prop="inStockBillState">
              <ElSelectBox :data="form" dataName="inStockBillState" :options="options.state" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据类型" prop="inStockType">
              <ElSelectBox :data="form" dataName="inStockType" :options="options.type" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="申请单号" prop="associationBillNo" v-if="form.inStockType !== 'InStockType5'">
              <ElInputBox :data="form" dataName="associationBillNo" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据备注" prop="inStockBillRemark" class="wAuto">
              <ElInputBox :data="form" dataName="inStockBillRemark" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox label="红冲原因" prop="redFlushReason" class="wAuto" v-if="!!form.redFlushReason">
              <ElInputBox :data="form" dataName="redFlushReason" type="textarea" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="作废原因" prop="disabledReason" class="wAuto" v-if="!!form.disabledReason">
              <ElInputBox :data="form" dataName="disabledReason" type="textarea" disabled />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="单据明细" isTop>
          <GoodList :data="{
            disabled: !isEdit,
            productionBatchAdd: true,
            height: 450,
            rowKey: 'specificationCode',
            prop: 'inStockDetailList',
            tbody: form.inStockDetailList,
            thead: [
              {
                label: '申请数量',
                prop: 'requestQuantity',
                align: 'center',
                width: 100,
              },
              {
                label: '生产批次',
                prop: 'productionBatchNumber',
                formType: 'number',
                isRules: true,
                align: 'center',
                width: 160,
              },
              {
                label: '生产日期',
                prop: 'productionDate',
                isRules: true,
                align: 'center',
                width: 120,
              },
              {
                label: '入库仓库',
                prop: 'areaShelfCode',
                formType: 'cascader',
                dataName: ['warehouseAreaCode', 'areaShelfCode'],
                options: options.warehouse,
                isRules: true,
                align: 'center',
                width: 180,
              },
              {
                label: '入库数量',
                prop: 'inStockQuantity',
                formType: 'number',
                isRules: true,
                align: 'center',
                width: 120,
              },
              {
                label: '备注',
                prop: 'inStockRemark',
                formType: 'textarea'
              },
            ],
            operation: [
              {
                label: '删除',
                icon: 'Delete',
              }
            ],
            addSelect: !!form.associationBillNo ? addSelect : null,
          }" @selectBtn="addMx">
          </GoodList>
        </CellBox>
      </div>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import { useListComponent } from '../pageTs'; // 引入逻辑
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
const { dataInfo, options } = useListComponent();
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    inStockBillNo: "", // 入库单号
    inStockType: "InStockType5", // 入库类型编码
    inStockBillState: 1, // 入库单据状态：1待确认；2待入库；3已入库；4已红冲；5已作废
    associationBillNo: "", // 申请单号
    requestUser: "", // 申请人员
    inStockBillRemark: "", // 备注
    createTime: "", // 创建时间
    createor: "", // 创建人员
    redFlushReason: "", // 红冲原因
    disabledReason: "", // 作废原因
    inStockDetailList: []
  },
});
const isEdit = ref(true)
const addSelect: any = reactive({
  title: '申请明细',
  rowKey: 'specificationCode',
  thead: [
    {
      label: '物料编号',
      prop: 'specificationCode',
      align: 'center',
      width: 120,
    },
    {
      label: '物料名称',
      prop: 'goodsName',
      align: 'left',
      width: null,
    },
    {
      label: '规格型号',
      prop: 'specificationName',
      align: 'center',
      width: 120,
    },
    {
      label: '类型',
      prop: 'goodsType',
      align: 'center',
      width: 120,
    },
    {
      label: '供应商',
      prop: 'supplierName',
      align: 'center',
      width: 260,
    },
    {
      label: '数量',
      prop: 'requestQuantity',
      align: 'center',
      width: 120,
    },
    {
      label: '单位',
      prop: 'goodsUnit',
      align: 'center',
      width: 120,
    },
  ],
  tbody: [],
})
//添加关联单明细
const addMx = (rows: any) => {
  const _rows = Array.isArray(rows) ? rows : [rows]
  let _arr = []
  if (!!data.form.associationBillNo) {
    //关联单入库
    _arr = _rows.map((el: any) => ({
      associationDetailNo: el.associationDetailNo, // 关联的申请单明细编码
      supplierCode: el.supplierCode, // 供应商编码
      goodsCode: el.goodsCode, // 物料编码
      specificationCode: el.specificationCode, // 规格编码
      requestQuantity: el.requestQuantity, // 申请数量
      inStockQuantity: el.requestQuantity, // 待入库数量
      inStockRemark: el.remark, // 申请数量
    }))
  } else {
    //其他入库
    _arr = _rows.map((el: any) => {
      const _productionBatch = el.details?.length > 0 ? el.details[0] : {}
      return {
        associationDetailNo: null, // 关联的申请单明细编码
        requestQuantity: 0, // 申请数量
        inStockQuantity: null, // 入库数量
        machineCode: '', // 入库数量
        goodsCode: el.goodsCode,// 物料编号
        supplierCode: el.supplierCode, // 供应商编码
        specificationCode: el.specificationCode, // 物料规格编码
        productionBatchCode: _productionBatch.productionBatchCode,//	生产批次编码
        productionBatchNumber: _productionBatch.productionBatchNumber,//	生产批次号
        productionDate: _productionBatch.productionDate ? proxy.$day(_productionBatch.productionDate) : '',//	生产日期
        warehouseAreaCode: _productionBatch.warehouseAreaCode,//	仓库分区代码
        areaShelfCode: _productionBatch.areaShelfCode,//	仓库分区代码
        stockGoodsCode: _productionBatch.stockGoodsCode,//	库存code
      }
    })
  }
  data.form.inStockDetailList.push(
    ..._arr
  )
}
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
//获取数据
const getForm = async () => {
  const _query: any = route.query
  setLoading()
  //是否新建
  if (!!!_query.code) {
    _getOrder(route.query)
    data.loading = false
    return
  }

  proxy.$api.InStockBill.GetSingleInStockBillView({
    queryBy: 0,
    queryValue: _query.code,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = ['1', '2'].includes(_query.type)
      data.form = res
      _getOrder(res)
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });

  function _getOrder(row: any) {
    //判断关联单号是否存在
    if (!!!row.associationBillNo) return
    const requestTypeObj: any = {
      InStockType2: 2,//采购退货
    }
    //获取关联单据明细
    proxy.$api.InStockBill.GetInStockRequestDetailBillList({
      type: requestTypeObj[row.inStockType || row.billType] || 1,//	单据类型：1物料采购，2生产退料
      associationBillNo: row.associationBillNo,//申请单号
    })
      .then((res: any) => {
        addSelect.tbody = res
        //是否存在关联单号
        if (!!data.form.associationBillNo) return
        data.form.associationBillNo = row.associationBillNo
        data.form.inStockType = row.billType
        addMx(res)
      })
      .catch(() => {

      });
  }
};
const saveBtn = (form: any, isConfirm: boolean = false, isPartial?: number) => {
  const _form: any = {
    inStockBillNo: form.inStockBillNo, // 入库单号
    associationBillNo: form.associationBillNo, // 业务单号（采购入库传采购单号，生产退料传退料单号）
    requestUserCode: form.requestUserCode || proxy.$user.UserCode, // 申请人员编号
    inStockType: form.inStockType, // 类型
    inStockBillRemark: form.inStockBillRemark, // 备注
    inStockBillMxList: form.inStockDetailList.map((el: any) => (
      {
        associationDetailNo: el.associationDetailNo || form.associationBillNo, // 关联的申请单明细编码
        supplierCode: el.supplierCode, // 供应商编码
        goodsCode: el.goodsCode, // 物料编码
        specificationCode: el.specificationCode, // 规格编码
        productionBatchCode: el.productionBatchCode, // 生产批次编码
        productionBatchNumber: el.productionBatchNumber, // 生产批次号
        productionDate: el.productionDate, // 生产日期
        warehouseAreaCode: el.warehouseAreaCode, // 仓库分区代码
        areaShelfCode: el.areaShelfCode, // 分区库位代码
        requestQuantity: el.requestQuantity, // 申请数量
        inStockQuantity: el.inStockQuantity, // 入库数量
        inStockRemark: el.inStockRemark, // 入库备注
      }
    ))
  }
  // return
  switch (route.query.type) {
    case '1'://新建
      proxy.$api.InStockBill.AddInStockBill(_form)
        .then((res: any) => {
          _form.inStockBillNo = res
          if (isConfirm) {
            _setState(_form, isPartial)
          } else {
            _sun()
          }
        })
        .catch(() => { });
      break;
    case '2'://编辑
      proxy.$api.InStockBill.UpdateInStockBill(_form)
        .then((res: any) => {
          if (isConfirm) {
            _setState(_form, isPartial)
          } else {
            _sun()
          }
        })
        .catch(() => { });
      break;
    default:
      break;
  }
  function _sun() {
    closeBtn('保存成功')
  }
  function _setState(form: any, isPartial?: number) {
    setState(form, 3, '', isPartial)
  }
};
const closeBtn = (message?: string) => {
  if (message) {
    proxy.$message(message)
  }
  sendMsg('save', true);
  // getForm()
  window.close();
};
const setState = (row: any, state: number = 1, reason: string = '', isPartial?: number) => {
  proxy.$api.InStockBill.UpdateInStockBillState({
    inStockBillNo: row.inStockBillNo,
    inStockBillState: state,//入库单据状态：1待确认；2待入库；3已入库；4已红冲；5已作废
    reason: reason,//原因
    isPartial: isPartial,//是否部分出库；0 完全出库，1 部分出库
  })
    .then((res: any) => {
      closeBtn('保存成功')
    })
    .catch(() => { });
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};

import { getInStockType, getWarehouse } from '@/utils/optionsArr.ts';
onMounted(() => {
  getForm();
  getInStockType(options, 'type')//获取设备
  getWarehouse(options, 'warehouse')//获取仓库
});
</script>
